<template>
  <TopMenu />
  <div class="flex flex-col min-h-screen p-4 bg-black gap-3">
    <!-- 页面标题（占比 1）-->
    <div
  class="flex-grow-[2] flex items-end justify-center text-4xl font-bold mb-4 
         bg-gradient-to-r from-black to-white bg-clip-text text-transparent"
>
  战例服务平台
</div>


    <!-- 统计卡片（占比 2）-->
    <div class="grid grid-cols-3 gap-4 mb-4 flex-grow-[4]">
      <StatCard title="当前素材数量" :count="countFile" color="#69c0ff" class="stat-card" />
      <StatCard title="当前战例数量" :count="countScene" color="#95de64" class="stat-card" />
      <StatCard title="当前主题数量" :count="countTag" color="#ffd666" class="stat-card" />
    </div>

    <!-- 分割线和下拉选择 -->
    <div class="flex items-center justify-between border-b pb-2 mb-2">
      <h2 class="text-lg font-semibold">{{ subtitle }}</h2>
      <ElSelect v-model="rankType" placeholder="请选择排名方式" @change="handleSelectChange" style="width: 160px">
        <ElOption label="按时间排名" value="time" />
        <ElOption label="按点击量排名" value="click" />
        <ElOption label="按时长排名" value="duration" />
      </ElSelect>
    </div>

    <!-- 卡片区（占比 3）-->
    <div class="flex-grow-[3] grid grid-cols-4 gap-4 overflow-auto mb-4">
      <ElCard v-for="item in sortedSceneList" :key="item.id" class="relative h-full overflow-hidden pb-0">
        <template #header>
          <div class="font-semibold">{{ item.description }}</div>
        </template>

        <!-- 卡片主体：背景图+按钮 -->
        <div class="relative w-full h-[30vh]" :style="getScenceBackgroundStyle(item)">
          <!-- 左下角浏览量 -->
          <div
            class="absolute left-3 bottom-3 flex items-center text-white text-sm gap-1 bg-black/50 px-2 py-1 rounded">
            <ElView />
            <span>{{ item.views }}</span>
          </div>

          <!-- 右下角按钮组 -->
          <div class="absolute right-3 bottom-3 flex gap-2">
            <ElTooltip content="播放" placement="top">
              <ElButton :icon="ElVideoPlay" circle size="small" @click="play(item)" />
            </ElTooltip>
            <ElTooltip content="编辑" placement="top">
              <ElButton :icon="ElEdit" circle size="small" @click="edit(item)" />
            </ElTooltip>
            <ElTooltip content="详情" placement="top">
              <ElButton :icon="ElInfoFilled" circle size="small" @click="detail(item)" />
            </ElTooltip>
          </div>
        </div>
      </ElCard>

    </div>


    <!-- 更多按钮 -->
    <div class="text-center mt-auto">
      <ElButton type="primary" @click="loadMore">更多</ElButton>
    </div>
  </div>
</template>


<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElSelect, ElOption, ElCard, ElButton, ElTooltip } from 'element-plus'
import { ElEdit, ElVideoPlay, ElInfoFilled, ElView } from '@vben/icons'
import { navApi } from '#/api'
import StatCard from '#/components/navigation/StatCard.vue'
import TopMenu from '#/components/navigation/TopMenu.vue'
import { useAccessStore } from '@vben/stores'

const defaultScence = 'http://localhost:3029/thumbnails/default.png'
const accessStore = useAccessStore()
const rankType = ref('time')
const subtitle = ref('按时间排名')
const sceneList = ref([] as any[]);
const fileList = ref([]);
const sceneTags = ref([]);
const sortedSceneList = computed(() => {
  const list = [...sceneList.value]; // 复制原始数据避免修改原数组

  switch (rankType.value) {
    case 'click':
      list.sort((a, b) => (b.views || 0) - (a.views || 0));
      break;
    case 'duration':
      list.sort((a, b) => (b.duration || 0) - (a.duration || 0));
      break;
    case 'time':
    default:
      list.sort((a, b) => {
        const dateA = new Date(a.createTime || a.created_at || 0).getTime();
        const dateB = new Date(b.createTime || b.created_at || 0).getTime();
        return dateB - dateA;
      });
      break;
  }

  return list.slice(0, 4); // 只取前 4 个
});

const getScenceBackgroundStyle = (item: any) => {
  const url = item.thumbnail?.trim();
  const backgroundUrl = url ? url : defaultScence;

  return {
    backgroundImage: `url(${backgroundUrl})`,
    backgroundSize: "cover",
    backgroundRepeat: "no-repeat",
    backgroundPosition: "center",
    crossorigin: "anonymous",
    cursor: "pointer"
  };
};

const handleSelectChange = (value: string) => {
  switch (value) {
    case 'time':
      subtitle.value = '按时间排名'
      break
    case 'click':
      subtitle.value = '按点击量排名'
      break
    case 'duration':
      subtitle.value = '按时长排名'
      break
  }
}

const play = (item: any) => {
  console.log('播放', item)
}

const edit = (item: any) => {
  console.log('编辑', item)
}

const detail = (item: any) => {
  console.log('详情', item)
}

const loadMore = () => {
  window.open(`http://localhost:8999/scene-preview?token=${accessStore.accessToken}`, '_blank')
}

// 动态计数（数量卡片）
const countFile = ref(0)
const countScene = ref(0)
const countTag = ref(0)

function animateCount(target: number, refVar: any, duration = 1000) {
  const frameRate = 20
  const steps = duration / frameRate
  let stepVal = target / steps
  let current = 0
  const interval = setInterval(() => {
    current += stepVal
    if (current >= target) {
      refVar.value = target
      clearInterval(interval)
    } else {
      refVar.value = Math.floor(current)
    }
  }, frameRate)
}

const initPlatformData = async () => {
  fileList.value = await navApi.getAllSceneAssets();
  sceneList.value = await navApi.getAllSceneList();
  sceneTags.value = await navApi.getSceneTags();
  console.log('fileList', fileList.value);
  console.log('sceneList', sceneList.value);
  console.log('sceneTags', sceneTags.value);
}

onMounted(async () => {
  try {
    await initPlatformData();
    animateCount(sceneList.value.length, countScene)
    animateCount(fileList.value.length, countFile)
    animateCount(sceneTags.value.length, countTag)
  } catch (error) {
    console.log(error)
  }

})
</script>

<style scoped>
.stat-card {
  transition: transform 0.3s, font-size 0.3s;
}

.stat-card:hover {
  transform: scale(1.05);
}

.stat-card:hover .text-3xl {
  font-size: 2.5rem;
}

.card {
  height: 100%;
  width: 100%;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  position: relative;
}
</style>
